<template>
  <div class="weDest" @click="intBlur">
    <div class="searchbox">
      <div class="line">
        <i class="el-icon-search"></i>
        <div class="int">
          <input type="text" v-model="searchKey" placeholder="点击搜索目的地/关键词" @focus="intFocus" @input="intChg" />
          <div class="showSearch" v-if="addressSearch && searchlist.length > 0">
            <div class="one" v-for="(item, i) in searchlist" :key="i" @click="sureAddress(item)">
              <div>{{ item.title }}</div>
              <span>{{ item.address }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div id="map"></div>
    <div class="selectbox">
      <div class="tit" v-if="village.length > 0">推荐目的地</div>
      <ul ref="village" v-if="village.length > 0">
        <li v-for="(item, i) in village" :key="i" @click="sureVillage(item)"
          :class="{ chk: checkLnglatSame(item.longitude, item.latitude) }">
          <i></i>
          <div class="info">
            <div>
              <span>{{ item.villageName }}</span>
              <p>
                <em v-for="(tag, j) in item.taglist" :key="j">{{ tag }}</em>
              </p>
            </div>
            <p>
              <span>{{ item.villageAddress }}</span><em>{{ item.distance }}km</em>
            </p>
          </div>
        </li>
      </ul>
      <div class="local" v-if="lastChk.show && lastChk.address" @click="sureLocal" :class="{
          chk: checkLnglatSame(lastChk.local.longitude, lastChk.local.latitude),
        }">
        <i></i>
        <span>{{ lastChk.address }}</span>
      </div>
      <div class="btn" @click="sureDest">
        <img src="@/assets/images/edit-icon.png" alt="" />确定目的地
      </div>
    </div>
  </div>
</template>

<script>
  window._AMapSecurityConfig = {
    securityJsCode: "1de37d2fc1b761d5ccacf8eee4b0c3b8",
  };
  import AMapLoader from "@amap/amap-jsapi-loader";
  import { getTravelMsg } from "@/api/wechat/navigation";
  export default {
    name: "weDest",
    data() {
      return {
        searchKey: null,
        addressSearch: false,
        searchlist: [],
        map: null,
        center: null,
        lastChk: {
          show: false,
          address: null,
          local: null,
        },
        lastIcon: null,
        circleIcon: null,
        dest: {
          address: null,
          local: null,
        },
        range: 10,
        geocoder: null,
        selectVillage: {},
        village: [],
        enterType: null,
        index: null,
      };
    },
    created() {
      if (this.$route.query && this.$route.query.longitude && this.$route.query.latitude) {
        this.center = [this.$route.query.longitude, this.$route.query.latitude];
      }
      this.enterType = this.$route.query.enterType;
      this.index = this.$route.query.index;
      if (this.enterType == 'editAdd' || this.enterType == 'editReplace') {
        document.title = "乡村选择";
      } else {
        document.title = "目的地选择";
      }

      this.setMap();
    },
    methods: {
      getTravelMsg(local, unClear) {
        if (Array.isArray(local) && local[0] && local[1]) {
          if (!unClear) {
            this.selectVillage = {}
          }
          getTravelMsg({
            longitude: local[0],
            latitude: local[1],
            startDistance: 0,
            endDistance: this.range,
          }).then((res) => {
            // console.log(res)
            res.data.forEach((item) => {
              if (item.villageLabel) {
                item.taglist = item.villageLabel.split(",");
              } else {
                item.taglist = [];
              }
            });
            this.village = res.data;
            this.setMarker();
            this.$nextTick(() => {
              if (!this.dest.local) {
                return false;
              }
              let chkIndex = null;
              this.village.forEach((item, i) => {
                if (this.checkLnglatSame(item.longitude, item.latitude)) {
                  chkIndex = i;
                }
              });
              if (chkIndex || chkIndex === 0) {
                this.$refs.village.scrollTop = 65 * chkIndex;
              }
            });
          });
        }
      },
      sureDest() {
        if (this.enterType) {
          if (!this.selectVillage.villageId) {
            this.$message.error("请确认选择乡村");
            return false;
          }
          this.$store.commit('SET_OPERATEINFO', {
            type: this.enterType,
            index: this.index,
            village: this.selectVillage
          });
          this.$router.go(-1)
        } else {
          if (!this.dest.local) {
            this.$message.error("请确认选择目的地");
            return false;
          }
          wx.miniProgram.getEnv((envRes) => {
            if (envRes.miniprogram) {
              wx.miniProgram.postMessage({ data: this.dest });
              wx.miniProgram.navigateBack(-1);
            }
          })
          tt.miniProgram.getEnv((envRes) => {
            if (envRes.miniprogram) {
              tt.miniProgram.postMessage({ data: this.dest });
              tt.miniProgram.navigateBack(-1);
            }
          })
        }
      },
      setMap() {
        AMapLoader.load({
            key: "c818b1b759eb2cad524fee31e071311c",
            version: "2.0",
            plugins: ["AMap.Geocoder"],
          })
          .then((AMap) => {
            this.geocoder = new AMap.Geocoder({});
            this.map = new AMap.Map("map", {
              zoom: 11,
              center: this.center || [119.65, 29.08],
              mapStyle: "amap://styles/54058aa0a123f042cdab644aaa6e580b",
              showIndoorMap: false,
            });

            this.lastIcon = new AMap.Icon({
              size: new AMap.Size(21, 28), // 图标尺寸
              image: require("../../assets/images/address-zs.png"), // Icon的图像
              imageOffset: new AMap.Pixel(0, 0), // 图像相对展示区域的偏移量，适于雪碧图等
              imageSize: new AMap.Size(21, 28), // 根据所设置的大小拉伸或压缩图片
            });

            this.circleIcon = new AMap.Icon({
              size: new AMap.Size(8, 8), // 图标尺寸
              image: require("../../assets/images/circle.jpg"), // Icon的图像
              imageOffset: new AMap.Pixel(0, 0), // 图像相对展示区域的偏移量，适于雪碧图等
              imageSize: new AMap.Size(8, 8), // 根据所设置的大小拉伸或压缩图片
            });

            if (this.center) {
              this.getAddressByLocal("map", this.center[0], this.center[1]);
            } else {
              this.getTravelMsg([119.65, 29.08]);
            }

            this.map.on("click", (e) => {
              this.getAddressByLocal("map", e.lnglat.lng, e.lnglat.lat);
            });
          }).catch((e) => {
            console.log(e);
          });
      },
      intChg() {
        if (!this.searchKey) {
          this.searchlist = [];
          return false;
        }

        this.$jsonp("https://apis.map.qq.com/ws/place/v1/suggestion", {
          key: "RITBZ-HBTL6-BFRSK-E266O-PPBH5-RCF4Q",
          keyword: this.searchKey, //用户输入的关键词，可设置固定值,如keyword:'KFC'
          // region: '金华市', //设置城市名，限制关键词所示的地域范围，非必填参数
          // region_fix: 1,
          page_size: 15,
          output: "jsonp",
        }).then((res) => {
          if (res.data && res.data.length > 0) {
            this.addressSearch = true;
            this.searchlist = res.data;
          }
        });
      },
      sureAddress(e) {
        let addressStr = e.city + e.district + e.title;
        this.getAddressByLocal("map", e.location.lng, e.location.lat, addressStr);
      },
      getAddressByLocal(clickType, lng, lat, addressStr, unClear) {
        this.geocoder.getAddress([lng, lat], (status, result) => {
          if (status === "complete" && result.info === "OK") {
            let backAddress =
              result.regeocode.addressComponent.district +
              result.regeocode.addressComponent.township +
              result.regeocode.addressComponent.street +
              result.regeocode.addressComponent.streetNumber;
            this.dest = {
              address: addressStr || result.regeocode.formattedAddress || backAddress,
              local: {
                longitude: lng,
                latitude: lat,
              },
            };
            this.lastChk = JSON.parse(JSON.stringify(this.dest));
            this.lastChk.show = clickType == "map";

            this.map.add(
              new AMap.Marker({
                position: [lng, lat],
              })
            );
            this.map.setCenter([lng, lat]);
            this.getTravelMsg([lng, lat], unClear);
          }
        });
      },
      setMarker() {
        this.map.clearMap();
        if (this.lastChk.local && this.lastChk.local.longitude && this.lastChk.local.latitude) {
          // 将 Icon 实例添加到 marker 上:
          let lastMarker = new AMap.Marker({
            position: new AMap.LngLat(this.lastChk.local.longitude, this.lastChk.local.latitude),
            offset: new AMap.Pixel(-10.5, -28),
            icon: this.lastIcon, // 添加 Icon 实例
            title: this.lastChk.address,
          });
          let circle = new AMap.Circle({
            center: new AMap.LngLat(this.lastChk.local.longitude, this.lastChk.local.latitude),
            radius: this.range * 200,
            strokeWeight: 0,
            fillColor: "#000",
            fillOpacity: 0.1,
          });
          circle.on("touchend", this.circleClick);
          let circle2 = new AMap.Circle({
            center: new AMap.LngLat(this.lastChk.local.longitude, this.lastChk.local.latitude),
            radius: this.range * 1000,
            strokeWeight: 0,
            fillColor: "#000",
            fillOpacity: 0.025,
          });
          circle2.on("touchend", this.circleClick);
          this.map.add(circle2);
          this.map.add(circle);
          this.map.add(lastMarker);
        }

        this.village.forEach((item) => {
          let vliiageCircle = new AMap.Marker({
            position: new AMap.LngLat(item.longitude, item.latitude),
            offset: new AMap.Pixel(-4, -4),
            icon: this.circleIcon,
            title: item.villageName,
            data: item,
          });
          vliiageCircle.on("touchend", this.villageClick);
          this.map.add(vliiageCircle);

          if (item.villageImage && !this.checkLnglatSame(item.longitude, item.latitude)) {
            let img = item.villageImage.split(",")[0];
            let content =
              `<img style="width:26px;height:26px;border-radius:4px" src="${process.env.VUE_APP_BASE_API + img}"/>`;

            let villageMarker = new AMap.Marker({
              position: new AMap.LngLat(item.longitude, item.latitude),
              content: content,
              offset: new AMap.Pixel(-26, -26),
              data: item,
            });
            villageMarker.on("touchend", this.villageClick2);
            this.map.add(villageMarker);
          }
        });
        this.map.setZoom(11);
      },
      circleClick(e) {
        this.getAddressByLocal("map", e.lnglat.lng, e.lnglat.lat);
      },
      villageClick(e) {
        let village = e.target._opts.data;
        this.selectVillage = village;
        this.getAddressByLocal(
          "vallage",
          village.longitude,
          village.latitude,
          village.villageName,
          true
        );
      },
      villageClick2(e) {
        let village = e.target._opts.data;
        this.selectVillage = village;
        this.getAddressByLocal(
          "vallage",
          village.longitude,
          village.latitude,
          village.villageName,
          true
        );
      },
      sureVillage(item) {
        this.selectVillage = item;
        this.getAddressByLocal(
          "vallage",
          item.longitude,
          item.latitude,
          item.villageName,
          true
        );
      },
      sureLocal() {
        if (this.lastChk.local) {
          this.getAddressByLocal(
            "map",
            this.lastChk.local.longitude,
            this.lastChk.local.latitude,
            this.lastChk.address
          );
        }
      },
      intFocus() {
        this.addressSearch = true;
        this.searchlist = [];
      },
      intBlur() {
        this.addressSearch = false;
        this.searchlist = [];
      },
      checkLnglatSame(lng, lat) {
        if (this.dest.local) {
          if (
            this.dest.local.longitude == lng &&
            this.dest.local.latitude == lat
          ) {
            return true;
          } else {
            return false;
          }
        } else {
          return false;
        }
      },
    },
  };
</script>
<style>
  .weDest .amap-logo,
  .weDest .amap-copyright {
    display: none !important;
  }
</style>
<style scoped lang="scss">
  .weDest {
    height: 100vh;
    display: flex;
    flex-direction: column;

    .searchbox {
      padding: 15px;
      background-color: #fff;

      .line {
        height: 40px;
        border-radius: 40px;
        display: flex;
        align-items: center;
        background-color: #F6F6F6;
        padding: 0 20px;

        i {
          font-size: 18px;
        }

        .int {
          flex: 1;
          height: 100%;
          margin-left: 10px;
          position: relative;

          input {
            font-size: 14px;
            width: 100%;
            height: 100%;
            background-color: transparent;
            border: none;
            outline: none;
          }

          .showSearch {
            width: 100%;
            max-height: 450px;
            border: 1px solid #4646a0;
            border-radius: 4px;
            text-align: left;
            background-color: #fff;
            position: absolute;
            left: 0;
            top: 100%;
            z-index: 999;
            overflow: auto;

            .one {
              height: 45px;
              display: flex;
              flex-direction: column;
              justify-content: center;
              padding: 0 10px;
              font-size: 14px;

              * {
                white-space: nowrap;
                text-overflow: ellipsis;
                overflow: hidden;
              }

              span {
                font-size: 12px;
                color: #666;
              }
            }
          }
        }
      }
    }

    #map {
      flex: 1;
    }

    .selectbox {
      font-size: 14px;
      color: #101010;
      padding: 15px 17px;
      background: #fff;

      ul {
        max-height: 260px;
        overflow-y: auto;
        margin: 0;
        padding: 0;

        li {
          list-style: none;
          padding: 10px 0;
          border-bottom: 1px solid #f0f0f0;
          display: flex;
          align-items: center;

          i {
            width: 12px;
            height: 12px;
            border-radius: 50%;
            border: 3px solid #b2b2ee;
            flex-shrink: 0;
          }

          &.chk {
            i {
              background-color: #4646a0;
              border-color: #4646a0;
            }
          }

          .info {
            margin-left: 15px;
            flex: 1;

            div {
              display: flex;
              align-items: center;

              span {
                font-size: 14px;
                font-weight: bold;
                margin-right: 10px;
              }

              p {
                flex: 1;
                width: 100px;
                overflow-x: auto;
                white-space: nowrap;
                margin: 0;

                em {
                  display: inline-block;
                  font-size: 10px;
                  font-style: normal;
                  color: #52b478;
                  background-color: #f1fdf8;
                  margin-left: 10px;
                  padding: 4px 8px;
                  line-height: 1;
                  border-radius: 4px;
                }
              }
            }

            &>p {
              font-size: 12px;
              margin: 6px 0 0;
              display: flex;

              span {
                flex: 1;
                white-space: nowrap;
                text-overflow: ellipsis;
                overflow: hidden;
                margin-right: 20px;
              }

              em {
                font-style: normal;
              }
            }
          }
        }
      }

      .local {
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 15px;

        i {
          flex-shrink: 0;
          width: 8px;
          height: 8px;
          border-radius: 50%;
          border: 3px solid #f9b9b9;
          margin-right: 10px;
        }

        &.chk {
          i {
            background-color: #ff9191;
            border-color: #ff9191;
          }
        }

        span {
          word-break: break-all;
        }
      }

      .btn {
        display: flex;
        color: #46469e;
        width: 100%;
        border-radius: 10px;
        background-color: #f5f5f9;
        padding: 10px;
        justify-content: center;
        align-items: center;
        font-size: 16px;

        img {
          height: 14px;
          margin: 0 10px 0 0;
        }
      }
    }
  }
</style>
